import common from "../../../lib/common/common.js";
import {
    createAGroupFolder,
    deletePlayerData,
    getPlayerData,
    isGroupExist,
    isPlayerExist,
    storagePlayerData
} from "../function/function.js";

export class Sm extends plugin {
    constructor() {
        super({
            name: '[Sm]我的奴隶',
            dsc: '我的奴隶',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]我的(奴隶|群友)$/, fnc: 'mySlave' }
            ]
        })
    }

    async mySlave(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用'])
        const ID = [e.user_id, e.group_id]

        if (!isGroupExist(ID[1])) {
            createAGroupFolder(ID[1])
        }

        if (!isPlayerExist(ID[1], ID[0])) {
            await storagePlayerData(ID[1], ID[0], {
                currency: 0,
                slave: [],
                value: 100,
                lastWorkingTime: 0,
                master: ''
            })
        }

        const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()])
        const userData = await getPlayerData(ID[1], ID[0])
        const { currency, slave, value, master } = userData
        const slaveNumber = slave.length

        // 判断主人是否还在群
        if (master !== '' && !memberInfoList[master]) {
            deletePlayerData(ID[1], master)
            userData['master'] = ''
            await storagePlayerData(ID[1], ID[0], userData)
        }
        let slaveInfo = [`# 基础信息\r金币: ${currency}\r身价: ${value}\r拥有奴隶数量: ${slaveNumber}\r主人: ${master === '' ? '无' : memberInfoList[master]['nickname']}`]
        if (slaveNumber === 0) {
            slaveInfo.push('你还没有奴隶')
        } else if (slaveNumber > 150) {
            slaveInfo.push('你的奴隶太多了...\r不予展示')
        } else {
            for (let i = 0; i < slaveNumber; i++) {
                // 判断奴隶是否还在群
                if (!memberInfoList[slave[i]]) {
                    deletePlayerData(ID[1], slave[i])
                    userData['slave'] = userData['slave'].filter(a => a !== slave[i])
                    await storagePlayerData(ID[1], ID[0], userData)
                    continue
                }
                let slaveInfos = []
                if (i < 30) {
                    slaveInfos.push(segment.image(`https://q1.qlogo.cn/g?b=qq&nk=${slave[i]}&s=160`))
                }
                const slaveData = await getPlayerData(ID[1], slave[i])
                slaveInfos.push(
                    `昵称: ${memberInfoList[slave[i]]['nickname']}\r`,
                    `QQ: ${slave[i]}\r`,
                    `身价: ${slaveData['value']}`
                )
                slaveInfo.push(slaveInfos)
            }
        }

        return e.reply(await common.makeForwardMsg(e, slaveInfo, 'MySlave', true))
    }
}